﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

namespace DatabaseGroup.SSIS.SourceAdapters
{
    public static class UpgradeHelper
    {
        public static void Upgrade(IDTSComponentMetaData100 componentMetaData, int newVersion)
        {
            UpgradeDelimiterPropertyTypeConverters(componentMetaData);

            switch (newVersion)
            {
                case 2:
                case 3:
                    UpgradeToVersion3(componentMetaData);
                    break;
            }
        }

        private static void UpgradeDelimiterPropertyTypeConverters(IDTSComponentMetaData100 componentMetaData)
        {
            List<string> delimiterColumns = new List<string>
                {
                    PropertiesManager.TextQualifierPropName,
                    PropertiesManager.HeaderRowDelimiterPropName,
                    PropertiesManager.ColumnDelimiterPropName,
                    PropertiesManager.RowDelimiterPropName
                };

            foreach (IDTSCustomProperty100 prop in componentMetaData.CustomPropertyCollection)
            {
                if (delimiterColumns.Contains(prop.Name))
                    prop.TypeConverter = typeof(DelimiterStringConverter).AssemblyQualifiedName;
            }
        }

        private static void UpgradeToVersion3(IDTSComponentMetaData100 componentMetaData)
        {
            bool delayValidationExists = false;

            foreach (IDTSCustomProperty100 prop in componentMetaData.CustomPropertyCollection)
            {
                if (prop.Name == PropertiesManager.DelayValidationPropName)
                {
                    delayValidationExists = true;
                    break;
                }
            }

            if (!delayValidationExists)
            {
                PropertiesManager.AddCustomProperty(componentMetaData.CustomPropertyCollection,
                    PropertiesManager.DelayValidationPropName, MessageStrings.DelayValidationPropDescription,
                    false, string.Empty);
            }
        }
    }
}
